<?php

function mysqldate(string $date){
	return preg_replace('#(\d{2})/(\d{2})/(\d{4})#', '$3-$2-$1', $date);
}

function calculateAge($birthDate){
	$tz = new DateTimeZone(TIMEZONE);
	return DateTime::createFromFormat('Y-m-d', $birthDate, $tz)->diff(new DateTime('now', $tz))->y;
}

function distance($lat1, $lng1, $lat2, $lng2, $meters = false){
	$pi80 = M_PI / 180;
	$lat1 *= $pi80;
	$lng1 *= $pi80;
	$lat2 *= $pi80;
	$lng2 *= $pi80;

	$r = 6372.797; // mean radius of Earth in km
	$dlat = $lat2 - $lat1;
	$dlng = $lng2 - $lng1;
	$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
	$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
	$km = $r * $c;

	return ($meters ? ($km * 1000) : $km);
}

function debugVariable($var, $context ="none"){
	logException(new ErrorException(var_export($var,true), 0, 0, $context, 1));
}

/** Returns a string with padding.
 * @param $num string the number to apply padding
 * @param $cant int the final size of string
 * @param $pad char optionally defines a different character to apply padding. */
function getNumWithPad($num, $cant = 3, $pad= '0'){
	return sprintf("%'".$pad.$cant."s", $num);
}

function getObjectForShareReport($presentation){
	$user = new User($presentation->attributes->userId);
	$obj = array();
	$obj["message"] = sprintf(langEcho("rp:share:message"), $user->attributes->firstName . " ". $user->attributes->lastName);
	$obj["subject"] = sprintf(langEcho("rp:share:subject"), $user->attributes->firstName . " ". $user->attributes->lastName, $presentation->attributes->name);
	return $obj;
}

function getObjectForShareHomeworkPresentation($presentation, $params = array(), &$session_uid = ""){
	$startParams = array();

	if ($params && isset($params["user"]) && ($params["user"]!="")){
		$user = $params["user"];
	} else {
		$user = getUserLoggedIn();
	}

	if ($params && isset($params["token"]) && isset($params["type"])){
		$startParams= array("token" => $params["token"],
							"type" => $params["type"],
							"device_uid" => "H" . $presentation->attributes->applicationUid,
							"presentation_uid" =>  $presentation->attributes->applicationUid,
							"homework" => true);
	} else {
		if($params && isset($params["password"]) && ($params["password"]!="")){
			$passKey = "password";
			$password = $params["password"];
		} else {
			$passKey = "passwordHash";
			$password = md5($user->attributes->password);
		}

		$startParams= array("username" => $user->attributes->userName,
		$passKey => $password,
								"device_uid" => "H" . $presentation->attributes->applicationUid,
								"presentation_uid" =>  $presentation->attributes->applicationUid,
								"homework" => true
		);
	}

	$result = call_rest_service_sync(PHOENIX_HUB_SERVICE . "session/start", $startParams,"json", "POST");

	if($result && $result["error_code"] == 0){
		$pin = strtoupper($result["pincode"]);
		$session_uid = $result["session_uid"];
	} else {
		return $result;
	}

	$obj = array();

	$pinLink = 'nearpod://pin='.$pin;
	$appStoreLink = 'http://itunes.apple.com/app/nearpod-app/id480295574?mt=8';

	$trialMessage = "";
	if(!$user->attributes->extendedFeatures){
		$trialMessage = sprintf(langEcho("shareHomeworkTrialExtraMessage"), MAX_HOMEWORKS_EXCEEDED);
	}

	$message = sprintf(langEcho("shareHomeworkMessage"), $pinLink, $pinLink, $pin, $appStoreLink, $appStoreLink);
	$obj["message"] = $message;
	$obj["trialMessage"] = $trialMessage;
	$obj["subject"] = sprintf(langEcho("shareHomeworkSubject"), $user->attributes->firstName, $user->attributes->lastName, $presentation->attributes->name);
	$obj["error_code"] = 0;

	return $obj;
}

function getObjectForSharePresentation($presentation){
	$uidgen = new UidGenerator();

	$sharePresentation = new SharePresentation();
	$sharePresentation->attributes->presentationId = $presentation->attributes->id;
	$sharePresentation->attributes->code = $uidgen->getUid();
	$sharePresentation->attributes->created = time();
	$sharePresentation->save(false,false);

	$user = new User($presentation->attributes->userId);
	$obj = array();
	$url = WWWROOT . "sharePresentation.php?code=" . $sharePresentation->attributes->code;
	$obj["message"] = sprintf(langEcho("sharePresentationMessage"), $url,$url);
	$obj["subject"] = $user->attributes->firstName . " ". $user->attributes->lastName . " " . langEcho("sharePresentatinSubject") . " (".$presentation->attributes->name.")";

	return $obj;
}

function hasFileSelector()
{
	if(preg_match('/(iphone|ipad|ipaq|ipod)/i', $_SERVER['HTTP_USER_AGENT'])){
		$iosVersion = preg_replace("/.*CPU.*OS ([0-9]).*/i", "$1", $_SERVER['HTTP_USER_AGENT']);
		if ($iosVersion == "6"){
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}

function isIOSDevice()
{
	if(preg_match('/(iphone|ipad|ipaq|ipod)/i', $_SERVER['HTTP_USER_AGENT']))
	return true;
	else
	return false;
}

function isMobile()
{
	if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT']))
	return true;

	else
	return false;
}

function isLanguageFile($lang){
	if ($lang=='en' || $lang=='es' || $lang=='pt'){
		$path = "language/".$lang.".php";
		if (file_exists(PATHROOT . $path)){
			return true;
		}
	}
	return false;
}

function encrypt($key, $string){
	$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
	return $encrypted;
}

function decrypt($key, $encrypted){
	$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
	return $decrypted;
}

function convertArrayToXML($fields) {
	$anyString = '';
	foreach ($fields as $key => $value) {
		$anyString = $anyString . '<' . $key . '><![CDATA[' . $value . ']]></' . $key . '>';
	}
	return $anyString;
}

function addXMLParent($xml,$parent) {
	return '<' . $parent . '>' . $xml . '</' . $parent . '>';
}

function PsExecute($command, $timeout = 60, $sleep = 2) {
	// First, execute the process, get the process ID

	$pid = PsExec($command);

	if( $pid === false )
	return false;

	$cur = 0;
	// Second, loop for $timeout seconds checking if process is running
	while( $cur < $timeout ) {
		sleep($sleep);
		$cur += $sleep;
		// If process is no longer running, return true;
		if( !PsExists($pid) )
		return true; // Process must have exited, success!
	}

	// If process is still running after timeout, kill the process and return false
	logException(new ErrorException($command, 0, 0, "exec command", 1));
	PsKill($pid);
	return false;
}

function PsExec($commandJob) {

	$command = $commandJob.' > /dev/null 2>&1 & echo $!';
	exec($command ,$op);
	$pid = (int)$op[0];

	if($pid!="") return $pid;

	return false;
}

function PsExists($pid) {
	exec("ps ax | grep $pid 2>&1", $output);
	while( list(,$row) = each($output) ) {

		$row_array = explode(" ", trim($row));
		$check_pid = $row_array[0];
		if($pid == $check_pid) {
			return true;
		}

	}

	return false;
}

function PsKill($pid) {
	exec("kill $pid", $output);

}


function trivialWord($word){
	$trivialWords="a, e, u, o, el, la, lo, las, los";
	return (strstr($trivialWords, $word));
}

/** Devuelve una cadena del tipo where field LIKE "%word%".
 * @param fields <p>
 * 	Array de campos a los que se quiere aplicar el filtro. <p>
 * <p>
 * @param rawQuery <p>
 * Un string conteniendo las palabras a buscar.
 * </p>
 */
function obtainFilterQuery($fields, $rawQuery){
	$where = "";
	if ($rawQuery != ''){
		$words = array();
		/* Tokenize */
		$delimiters = " \n\t+,;:.";
		$tok = strtok($rawQuery, $delimiters);
		while ($tok !== false) {
			if (!trivialWord($tok))
			$words[] = $tok;
			$tok = strtok($delimiters);
		}
		/* Build where clause */
		$where = " ";
		foreach($words as $word){
			$where.= "(";
			foreach($fields as $field){
				$where .= " $field LIKE '%$word%' OR";
			}
			$where = substr($where, 0, -2); // delete last |
			$where.= " ) AND";
		}
		$where = substr($where, 0, -3); // delete last |
	}
	return $where;
}

function strToLenght($string, $lenght){
	if(strlen($string) > $lenght)
	$string = substr($string,0,$lenght-3)."...";
	return $string;
}

/**
 * returns an array indexed by the $keyField. If the key field is an array the index would be each $keyField
 * value followed by $glue
 *
 * @param array $arIndexed the array
 * @param mixed $keyField string or array
 * @param bool $multipleKeyValues if each key could contain more than one element (DEFAULT: false)
 * @param string $glue (DEFAULT: ".")
 * @return array indexed
 */
function indexedToKeyedArray($arIndexed, $keyField, $multipleKeyValues = false, $glue = ".") {
	$result = array();
	foreach($arIndexed as $entry) {
		$key = "";
		if(is_array($keyField)){
			foreach($keyField as $field){
				if($key == ""){
					if(isset($entry[$field])){
						$key = $entry[$field];
					}
				}else{
					$key .= $glue;
					if(isset($entry[$field])){
						$key .= $entry[$field];
					}
				}
			}
		}else{
			$key = $entry[$keyField];
		}
		if($multipleKeyValues){
			if(!isset($result[$key])){
				$result[$key] = array();
			}
			$result[$key][] = $entry;
		}else{
			$result[$key] = $entry;
		}
	}
	return $result;
}

function orderBySlide( $a, $b )
{
	if(  $a["slide"] ==  $b["slide"] ){
		return 0 ;
	}
	return ($a["slide"] < $b["slide"]) ? -1 : 1;
}

function orderArrayByArrayValue($array, $keyToOrder, $sort = SORT_ASC){
	$newArray = array();
	foreach ($array as $key => $row)
	{
		$newArray[$key] = $row[$keyToOrder];
	}
	array_multisort($newArray, $sort, $array);

	return $array;
}

function addKeyValueToArray($key, $value, &$array){
	foreach($array as $array_key => $values){
		$array[$array_key][$key] = $value;
	}
}

/**
 * Copia un archivo desde el origen al destino creando todas las carpetas intermedias del destino.
 *
 * @param source <p>
 * 	Path completo del archivo de origen. <p>
 * <p>
 * @param dest <p>
 * 	Path completo del archivo destino.
 * </p>
 * @return 'true' si pudo completar la operaciÃ³n, 'false' en caso contrario.
 */
function saveFile($source, $dest) {
	if (file_exists($source)) {
		$dirs = explode("/", $dest);
		$completeDir = "/";
		for($i = 0; $i < count($dirs) - 1; $i++){
			$completeDir .= $dirs[$i] . "/";
			if (!file_exists($completeDir)){
				mkdir($completeDir);
			}
		}
		copy($source, $dest);
		return true;
	}
	return false;
}

/**
 * Crea todas las carpetas del string de tipo /path/del/archivo.
 *
 * @param path <p>
 * 	Path completo del archivo de origen. <p>
 * <p> */
function createPath($path) {
	$dirs = explode(DIRECTORY_SEPARATOR, $path);
	$completeDir = "";
	if($dirs[0] != ""){
		$i = 0;
	}else{
		$i = 1;
		$completeDir .= DIRECTORY_SEPARATOR;
	}

	for($i; $i < count($dirs) -1; $i++){
		$completeDir .= $dirs[$i] . DIRECTORY_SEPARATOR;
		if (!file_exists($completeDir)){
			mkdir($completeDir);
		}
	}
}

function userListText($text){
	return ($text)?$text:"<i>".langEcho("no:specified")."</i>";
}

function boolToYesNo($bool){
	return ($bool)?langEcho("Yes"):langEcho("No");
}

function getLanguagePlist($key){
	return getLanguageName($key) . ".plist";
}

function getLanguageName($key){
	$languages = array("en" => "English",
						"pt" => "Portuguese",
						"es" => "Spanish");
	return $languages[$key];
}

function getValueFromFile($filename, $key){
	if (fileExists($filename)) {
		$file = fileGetContents($filename);
		if($file){
			$configs = parse_ini_string($file,false);
			if(isset($configs[$key])){
				return trim($configs[$key]);
			}
		}
	}
	return null;
}

function getImageSizeFromRelativePath($fileRelativePath){
	switch(UPLOADTO){
		case UPLOADLOCAL:
			return getimagesize(UPLOADPATH.$fileRelativePath);
			break;
		case UPLOADAMAZONS3:
			// FIXME ver si funciona en amazon
			return getimagesize(UPLOADWWW . $fileRelativePath);
			break;
	}
	return false;
}

function getFileSize($fileRelativePath){
	switch(UPLOADTO){
		case UPLOADLOCAL:
			return filesize(UPLOADPATH.$fileRelativePath);
			break;
		case UPLOADAMAZONS3:
			$counter = 0;
			//tries twice
			while($counter < 2){
				try {
					$s3 = new AmazonS3();
					return $s3->get_object_filesize(AMAZONS3BUCKET, AMAZONS3MAINFOLDER . $fileRelativePath);
				} catch (Exception $e) {
					$counter++;
					if($counter >= 2){
						throw $e;
					}
				}
			}

			break;
	}
	return false;
}

function fileExists($fileRelativePath){
	GLOBAL $isDemoPresentation;
	if ($isDemoPresentation){
		return file_exists(UPLOADPATH.$fileRelativePath);
	} else {
		switch(UPLOADTO){
			case UPLOADLOCAL:
				return file_exists(UPLOADPATH.$fileRelativePath);
				break;
			case UPLOADAMAZONS3:
				$counter = 0;
				//tries twice
				while($counter < 2){
					try {
						$s3 = new AmazonS3();
						return $s3->if_object_exists(AMAZONS3BUCKET, AMAZONS3MAINFOLDER . $fileRelativePath);
					} catch (Exception $e) {
						$counter++;
						if($counter >= 2){
							throw $e;
						}
					}
				}
				break;
		}
	}
	return false;
}

function copyFromToLocal($from, $to){
	if (fileExists($from)){
		createPath($to);
		file_put_contents($to, fileGetContents($from));
	}
}

function savePList($plist, $savePath){
	$plistDict = $plist->getValue();
	$plistDict->add("version",new CFString(PLIST_VERSION));
	$plist->saveXML( $savePath );
}

function savePListFromName($filename, $savePath){
	$plist = new CFPropertyList($filename);
	savePList($plist, $savePath);
}

function fileGetContents($fileRelativePath){
	GLOBAL $isDemoPresentation;
	if ($isDemoPresentation){
		return file_get_contents(UPLOADPATH.$fileRelativePath);
	} else {
		switch(UPLOADTO){
			case UPLOADLOCAL:
				return file_get_contents(UPLOADPATH.$fileRelativePath);
				break;
			case UPLOADAMAZONS3:
				$counter = 0;
				//tries twice
				while($counter < 2){
					try {
						$s3 = new AmazonS3();
						$response = $s3->get_object(AMAZONS3BUCKET, AMAZONS3MAINFOLDER .$fileRelativePath );
						return $response->body;
					} catch (Exception $e) {
						$counter++;
						if($counter >= 2){
							throw $e;
						}
					}
				}
				break;
		}
	}
	return false;
}

/* HARDCODE JR.*/
function copyDemofile($srcRelative, $destRelative){
	createPath(UPLOADPATH . $destRelative);
	copy(UPLOADPATH . $srcRelative, UPLOADPATH . $destRelative);
}
/* END HARDCODE JR*/

function copy_file($srcRelative, $destRelative){
	switch(UPLOADTO){
		case UPLOADLOCAL:
			createPath(UPLOADPATH . $destRelative);
			copy(UPLOADPATH . $srcRelative, UPLOADPATH . $destRelative);
			break;
		case UPLOADAMAZONS3:
			$counter = 0;
			//tries twice
			while($counter < 2){
				try {
					$s3 = new AmazonS3();
					$src = array("filename" => AMAZONS3MAINFOLDER . $srcRelative, "bucket" => AMAZONS3BUCKET);
					$destination = array("filename" => AMAZONS3MAINFOLDER . $destRelative, "bucket" => AMAZONS3BUCKET);
					$options = array('acl' => AmazonS3::ACL_PUBLIC);
					$response = $s3->copy_object($src, $destination, $options);
					return;
				} catch (Exception $e) {
					$counter++;
					if($counter >= 2){
						throw $e;
					}
				}
			}
			break;
	}

}

function copy_file_async($srcRelative, $destRelative){
	$url = WWWROOT."service/service.php";
	$params = array("method" => "copyFile","sourceRelative" => $srcRelative,"destinationRelative" => $destRelative);
	call_rest_service_post_async($url, $params);
}


///**
//* Deletes all Amazon S3 objects inside the specified bucket.
//*
//* @param string $bucket (Required) The name of the bucket to use.
//* @param string $folder (Required) The folder
//* @return boolean A value of <code>true</code> means that all objects were successfully deleted. A value of <code>false</code> means that at least one object failed to delete.
//* @link http://php.net/pcre Regular Expressions (Perl-Compatible)
//*/
// function amazons3_delete_folder($bucket, $folder)
// {
// 	$s3 = new AmazonS3();
// 	// Collect all matches
// 	$list = $s3->get_object_list($bucket, array('prefix' => $folder, 'pcre' => AmazonS3::PCRE_ALL));

// 	// As long as we have at least one match...
// 	if (count($list) > 0)
// 	{
// 		$objects = array();

// 		foreach ($list as $object)
// 		{
// 			$objects[] = array('key' => $object);
// 		}

// 		$response = $s3->delete_objects($bucket, array(
// 				'objects' => $objects
// 		));

// 		return ($response->isOK() && !isset($response->body->Error));
// 	}

// 	// If there are no matches, return true
// 	return true;
// }

function getNumberOfElements($relativeFolderPath){
	switch(UPLOADTO){
		case UPLOADLOCAL:
			var_dump(UPLOADPATH . $relativeFolderPath);
			$count = count(getDirectoryList(UPLOADPATH . $relativeFolderPath));
			break;
		case UPLOADAMAZONS3:
			$counter = 0;
			//tries twice
			while($counter < 2){
				try {
					$s3 = new AmazonS3();
					$prefix = AMAZONS3MAINFOLDER . $relativeFolderPath;
					$response = $s3->get_object_list(AMAZONS3BUCKET, array("prefix" => $prefix));
					$count = count ($response);
					var_dump($response);
					return;
				} catch (Exception $e) {
					$counter++;
					if($counter >= 2){
						throw $e;
					}
				}
			}
			break;
	}
	return $count;
}

function saveUploadFile($relativePath, $content){
	switch(UPLOADTO){
		case UPLOADLOCAL:
			createPath(UPLOADPATH . $relativePath);
			file_put_contents(UPLOADPATH . $relativePath, $content);
			break;
		case UPLOADAMAZONS3:
			$counter = 0;
			//tries twice
			while($counter < 2){
				try {
					if(AMAZONS3_DO_BACKUP){
						if(fileExists($relativePath)){
							$s3 = new AmazonS3();
							$src = array("filename" => AMAZONS3MAINFOLDER . $relativePath, "bucket" => AMAZONS3BUCKET);
							$destination = array("filename" => AMAZONS3BUCKET . "/" . AMAZONS3MAINFOLDER . $relativePath, "bucket" => AMAZONS3_BUCKET_BACKUP);
							$options = array('acl' => AmazonS3::ACL_PUBLIC);
							$response = $s3->copy_object($src, $destination, $options);
						}
					}

					$s3 = new AmazonS3();
					$tempDir = TEMP_PATH ."/";

					$parts = explode("/", $relativePath);
					$filename = $parts[sizeof($parts) -1];
					$tempFilePath = $tempDir . "/" . str_replace(".","",str_replace(" ","",microtime())) .  $filename;
					createPath($tempFilePath);
					file_put_contents($tempFilePath, $content);

					$response = $s3->create_object(AMAZONS3BUCKET, AMAZONS3MAINFOLDER .  $relativePath, array(
							'fileUpload' => $tempFilePath,
							'acl' => AmazonS3::ACL_PUBLIC
					));

					unlink($tempFilePath);
					return;
				} catch (Exception $e) {
					$counter++;
					if($counter >= 2){
						throw $e;
					}
				}
			}
			break;
	}
}

function saveUploadFolder($relativePath, $folder, $exclude = array()){
	$files = getDirectoryList($folder);
	foreach ($files as $file){
		if(is_dir($folder . "/". $file)){
			saveUploadFolder($relativePath . $file . "/",  $folder. "/" .$file, $exclude);
		}else if(!in_array($file, $exclude)){
			//			var_dump("Guardando en.. " .$relativePath . $file);
			saveUploadFile($relativePath . $file, file_get_contents($folder . "/". $file));
		}
	}
}

function saveUploadFileAsync($srcRelative, $content){
	$path = TEMP_PATH . "/file_" . str_replace(".","",str_replace(" ","",microtime()));
	createPath($path);
	file_put_contents($path, $content);
	exec(COMMAND_CLI." ".PATHROOT."start.php f=service/service.php method=saveUpload sourceRelative=".$srcRelative." filePath=".$path." > /dev/null 2>/dev/null &");
}

function saveUploadFolderFromLocalAsync($relativePath, $folder, $exclude = array()){
	$files = getDirectoryList($folder);

	foreach ($files as $file){
		if(is_dir($folder . "/". $file)){
			saveUploadFolderFromLocalAsync($relativePath . $file . "/",  $folder. "/" .$file, $exclude);
		}else if(!in_array($file, $exclude)){
			saveUploadFileAsync($relativePath . $file, file_get_contents($folder . "/". $file));
		}
	}
}

function getFilesUrlFromDirRec($dir, $array, $relativePath){
	$files = getDirectoryList($dir);
	foreach($files as $file){
		if(is_dir($dir."/".$file)){
			$array = getFilesUrlFromDirRec($dir."/".$file,$array,$relativePath."/".$file);
		}else{
			$array[] =  UPLOADCDN.$relativePath."/".$file;
		}
	}
	return $array;
}

function htmlCharReplace($string)
{
	$string = str_replace(array("&lt;", "&gt;", '&amp;', '&#39;', '&quot;','&lt;', '&gt;', '&#34;'), array("<", ">",'&','\'','"','<','>','"'), htmlspecialchars_decode($string, ENT_NOQUOTES));
	return $string;
}

function escapeQuote($string){
	$string = str_replace("'","&#39;" ,$string);
	$string = str_replace('"', "&#34;" ,$string);
	return $string;
}

function stringCaseInsensitiveCompare($a, $b) {
	if (strtolower($a) == strtolower($b)) {
		return 0;
	}
	return (strtolower($a) < strtolower($b)) ? -1 : 1;
}

function htmlnumericentities($str){
	return preg_replace('/[^!-%\x27-;=?-~ ]/e', '"&#".ord("$0").chr(59)', $str);
}

function authenticateCompany($userName, $password, $passwordHash = ""){
	return authenticateUser($userName, $password, $passwordHash) &&
		User::getByUserName($userName)->isCompany();
}

function authenticateUser($userName, $password, $passwordHash = ""){
	if($userName == "root" && $password == USER_ROOT_PASS){
		return true;
	}
	$userManager = new User();

	$userUserName = User::getByUserName($userName);

	if ($userUserName->attributes){
		if ($passwordHash){
			if (md5($userUserName->attributes->password) == $passwordHash){
				return true;
			}
		} else {
			if ($userUserName->attributes->password == $userManager->getPassword($password,true)){
				return true;
			}
		}
	}
	return false;
}

function redirectIfNotPermited($roles, $user = null){
	if(!validateUserPermission($roles, $user)){
		logError(langEcho("permission:access:denied"));
		forward(WWWROOT . "login.php?url=" . urlencode(curPageURL()));
	}
}

function validateUserPermission($roles, $user = null){
	if(isAdminLoggedIn()){
		return true;
	}
	if(!isset($user)){
		if(isset($_SESSION["userroleid"])){
			$roleId = $_SESSION["userroleid"];
		}else{
			return false;
		}
	}else{
		$roleId = $user->attributes->roleId;
	}

	if(!is_array($roles)){
		$roles = array($roles);
	}
	return in_array($roleId, $roles);
}

function redirectIfNotAdmin(){
	if(!isAdminLoggedIn()){
		logError(langEcho("permission:access:denied"));
		forward(WWWROOT . "login.php?url=" . urlencode(curPageURL()));
	}
}

function isAdminLoggedIn(){
	if(isUserLoggedIn()){
		return $_SESSION['useradmin'];
	}
	return false;
}

function isUserLoggedIn(){
	if(isset($_SESSION["userid"]) && $_SESSION["userid"] > 0){
		return true;
	}

	if(isset($_COOKIE["userid"]) && $_COOKIE["userid"] > 0){
		return loginUser(new User($_COOKIE["userid"]));
	}

	return false;
}

function loginUser($user, $remember = false){
	if (isset($user->attributes->id) && $user->attributes->id > 0){
		$_SESSION['userid'] = $user->attributes->id;
		$_SESSION['username'] = $user->attributes->username;
		//	$_SESSION['userlang'] = $user->attributes->lang;
		// FIXME harcoded adminId = 1 (however it's more secure than put it by config)
		$_SESSION['useradmin'] = $user->isAdmin();
		//	$_SESSION['userroleid'] = $user->attributes->roleId;
		//	$_SESSION['userfirstname'] = $user->attributes->firstName;
		//	$_SESSION['userlastname'] = $user->attributes->lastName;
		//	$_SESSION['userprevlastlogin'] = $user->attributes->lastLogin;
		//	$user->attributes->lastLogin = time();
		$user->save(false,false,false);
		if($remember){
			setcookie("userid", $user->attributes->id,time() + (86400 * 7), '/');
		}
		return true;
	}

	$_SESSION['user'] = "";
	return false;
}

function logout(){
	session_unset();
	setcookie("userid","",time() - 3600, "/");
}

function getUserLoggedIn(){
	if(isUserLoggedIn()){
		return new User($_SESSION["userid"]);
	}

	return null;
}

function getUserLoggedInId(){
	if(isUserLoggedIn()){
		return $_SESSION['userid'];
	}

	return null;
}

function curPageURL() {
	if(PHP_SAPI == "cli"){
		return "";
	}

	$pageURL = 'http';
	if ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") || (isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && $_SERVER["HTTP_X_FORWARDED_PROTO"] == "https" ) ){
		$pageURL .= "s";
	}
	$pageURL .= "://";
	if (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	return $pageURL;
}

function curPageBasic() {

	$page = curPageURL();
	$questionSign = strpos($page, '?');
	if($questionSign > 0)
	$newPage = substr($page, 0,$questionSign);
	else
	$newPage = $page;

	return $newPage;
}


function contains($string, $search){
	$pos = strpos($string,$search);

	if($pos === false) {
		return false;
	}
	else {
		return true;
	}
}

function forward($location = "") {
	if (!headers_sent()) {
		if ($location) {
			header("Location: {$location}");
			exit;
		} else if ($location === '') {
			exit;
		}
	}

	return false;
}

function getInput($key, $default = '', $trim = true){
	return getInputArray($key, $_REQUEST, $default, $trim);
}

function getInputArray($key, $array, $default = '', $trim = true){
	$return = $default;
	if(array_key_exists($key,$array) && $array[$key] !== ''){
		if($trim && !is_array($array[$key]) && !is_object($array[$key])){
			$return = trim($array[$key]);
		}else{
			$return = $array[$key];
		}
	}
	return $return;
}


function getIcon($class, $id, $size = "normal"){
	$file = UPLOADPATH . $class . "/" . $id . "/icon" . $size .".jpg";

	if (file_exists($file)){
		return UPLOADWWW . $class . "/" . $id . "/icon" . $size .".jpg";
	}else{
		return WWWROOT .  "images/" . $class . "/icon" . $size .".jpg";
	}
}

function generatePassword($length=6,$level=2){

	list($usec, $sec) = explode(' ', microtime());
	srand((float) $sec + ((float) $usec * 100000));

	$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
	$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";

	$password  = "";
	$counter   = 0;

	while ($counter < $length) {
		$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

		// All character must be different
		if (!strstr($password, $actChar)) {
			$password .= $actChar;
			$counter++;
		}
	}

	return $password;
}

function getExtension($filename){
	$array = explode(".", $filename);
	if (sizeof($array)==1){
		return "";
	}
	return array_pop($array);
}

function getCustomPath($id){
	return "Presentation/" . $id . "/custom/";
}

function getRelativeImagePaths(){
	return array(			"config" => "config",
							"defaultPushableContent" => "flash/defaultPushableContent.png",
							"leadnode" => "flash/leadnode.png",
							"quizstats" => "flash/quizstats.png",
							"watchVideo" => "flash/watchVideo.png",
							"poll" => "flash/poll.png",
							"quizstart" => "flash/quizstats.png",
	//ios ipad
	//leads
							"leads_bg_ipad" => "ios/ipad/leads/leads_bg.png",
	//miscelaneous imgs
							"background_ipad" => "ios/ipad/miscelaneous/background.png",
							"confirmation_back_ipad" => "ios/ipad/miscelaneous/confirmation_back.png",
							"lookscreen_ipad" => "ios/ipad/miscelaneous/lookscreen.png",
							"lookvideo_ipad" => "ios/ipad/miscelaneous/lookvideo.png",
							"pleasewait_ipad" => "ios/ipad/miscelaneous/pleasewait.png",
	//miscelaneous buttons
							"00-ButtonBack_p_ipad" => "ios/ipad/miscelaneous/00-ButtonBack_p.png",
							"00-ButtonBack_ipad" => "ios/ipad/miscelaneous/00-ButtonBack.png",
							"00-ButtonContinue_p_ipad" => "ios/ipad/miscelaneous/00-ButtonContinue_p.png",
							"00-ButtonContinue_ipad" => "ios/ipad/miscelaneous/00-ButtonContinue.png",
							"00-ButtonSubmit_p_ipad" => "ios/ipad/miscelaneous/00-ButtonSubmit_p.png",
							"00-ButtonSubmit_ipad" => "ios/ipad/miscelaneous/00-ButtonSubmit.png",
							"back_btn_en_p_ipad" => "ios/ipad/miscelaneous/back_btn_en_p.png",
							"back_btn_en_ipad" => "ios/ipad/miscelaneous/back_btn_en.png",
							"next_btn_en_p_ipad" => "ios/ipad/miscelaneous/next_btn_en_p.png",
							"next_btn_en_ipad" => "ios/ipad/miscelaneous/next_btn_en.png",
							"01_field_ipad" => "ios/ipad/miscelaneous/01-Field.png",
	//poll
							"poll_bg_ipad" => "ios/ipad/poll/poll_bg.png",
							"score_bg_ipad" => "ios/ipad/poll/score_bg.png",
							"scrollBar_ipad" => "ios/ipad/poll/scrollBar.png",
							"multiline_ipad" => "ios/ipad/poll/multiline.png",
							"canvas_ipad" => "ios/ipad/poll/canvas.png",
							"quizstart" => "ios/ipad/poll/quizstart.png",
	//ios ipod
	//leads
							"leads_bg_ipod" => "ios/ipod/leads/leads_bg.png",
							"leads_bg_ipod_2" => "ios/ipod/leads/leads_bg@2x.png",
	//miscelaneous images
							"background_ipod" => "ios/ipod/miscelaneous/background.png",
							"background_ipod_2" => "ios/ipod/miscelaneous/background@2x.png",
							"confirmation_back_ipod" => "ios/ipod/miscelaneous/confirmation_back.png",
							"confirmation_back_ipod_2" => "ios/ipod/miscelaneous/confirmation_back@2x.png",
							"lookscreen_ipod" => "ios/ipod/miscelaneous/lookscreen.png",
							"lookscreen_ipod_2" => "ios/ipod/miscelaneous/lookscreen@2x.png",
							"lookvideo_ipod" => "ios/ipod/miscelaneous/lookvideo.png",
							"lookvideo_ipod_2" => "ios/ipod/miscelaneous/lookvideo@2x.png",
							"pleasewait_ipod" => "ios/ipod/miscelaneous/pleasewait.png",
							"pleasewait_ipod_2" => "ios/ipod/miscelaneous/pleasewait@2x.png",
	//miscelaneous buttons
							"00-ButtonBack_p_ipod" => "ios/ipod/miscelaneous/00-ButtonBack_p.png",
							"00-ButtonBack_ipod" => "ios/ipod/miscelaneous/00-ButtonBack.png",
							"00-ButtonContinue_p_ipod" => "ios/ipod/miscelaneous/00-ButtonContinue_p.png",
							"00-ButtonContinue_ipod" => "ios/ipod/miscelaneous/00-ButtonContinue.png",
							"00-ButtonSubmit_p_ipod" => "ios/ipod/miscelaneous/00-ButtonSubmit_p.png",
							"00-ButtonSubmit_p_ipod_2" => "ios/ipod/miscelaneous/00-ButtonSubmit_p@2x.png",
							"00-ButtonSubmit_ipod" => "ios/ipod/miscelaneous/00-ButtonSubmit.png",
							"00-ButtonSubmit_ipod_2" => "ios/ipod/miscelaneous/00-ButtonSubmit@2x.png",
							"back_btn_en_p_ipod" => "ios/ipod/miscelaneous/back_btn_en_p.png",
							"back_btn_en_p_ipod_2" => "ios/ipod/miscelaneous/back_btn_en_p@2x.png",
							"back_btn_en_ipod" => "ios/ipod/miscelaneous/back_btn_en.png",
							"back_btn_en_ipod_2" => "ios/ipod/miscelaneous/back_btn_en@2x.png",
							"next_btn_en_p_ipod" => "ios/ipod/miscelaneous/next_btn_en_p.png",
							"next_btn_en_p_ipod_2" => "ios/ipod/miscelaneous/next_btn_en_p@2x.png",
							"next_btn_en_ipod" => "ios/ipod/miscelaneous/next_btn_en.png",
							"next_btn_en_ipod_2" => "ios/ipod/miscelaneous/next_btn_en@2x.png",
							"01_field_ipod" => "ios/ipod/miscelaneous/01-Field.png",
							"01_field_ipod_2" => "ios/ipod/miscelaneous/01-Field@2x.png",
	//poll
							"poll_bg_ipod" => "ios/ipod/poll/poll_bg.png",
							"poll_bg_ipod_2" => "ios/ipod/poll/poll_bg@2x.png",
							"scrollBar_ipod" => "ios/ipod/poll/scrollBar.png",
							"scrollBar_ipod_2" => "ios/ipod/poll/scrollBar@2x.png",
							"multiline_ipod" => "ios/ipod/poll/multiline.png",
							"multiline_ipod_2" => "ios/ipod/poll/multiline@2x.png",
							"score_bg_ipod_2" => "ios/ipod/poll/score_bg@2x.png",
							"score_bg_ipod" => "ios/ipod/poll/score_bg.png",
							"canvas_ipod" => "ios/ipod/poll/canvas.png",
							"canvas_ipod_2" => "ios/ipod/poll/canvas@2x.png",
							"quizstart_ipod" => "ios/ipod/poll/quizstart.png",
							"quizstart_ipod_2" => "ios/ipod/poll/quizstart@2x.png",
	);
}

function validateImageFile($image){
	return validateImageFileByMime($image);
}

function validateZipFile($file){
	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $finfo->file($file['tmp_name']);
	$zipTypes = explode(",", ZIPEXTENSIONS);
	foreach($zipTypes as $type){
		if(($type == $mime)){
			return true;
		}
	}
	return false;
}

function validateImageFileByMime($image){
	$imagesTypes = explode(",", IMAGEEXTENSIONS);
	$imageData = getimagesize($image);
	foreach($imagesTypes as $type){
		if($type == $imageData["mime"]){
			return true;
		}
	}
	return false;
}

function validateImageFileByExtension($image, $extensions = null){
	$extensions = ($extensions)? $extensions:IMAGEEXTENSIONS;
	$imagesTypes = explode(",", $extensions);

	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $finfo->file($image['tmp_name']);
	//$imageData = getimagesize($image);
	foreach($imagesTypes as $type){
		if($type == $mime){
			return true;
		}
	}
	return false;
}

function getFileExtension($fileName){
	$vars = explode('.', $fileName);
	return $vars[count($vars)-1];
}

function validateVideoFile($video){
	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $finfo->file($video['tmp_name']);
	$videoTypes = explode(",", VIDEOEXTENSIONS);
	foreach($videoTypes as $type){
		if($type == $mime){
			return true;
		}
	}
	return false;
}

function validatePDF($pdf){
	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $finfo->file($pdf['tmp_name']);
	$pdfTypes = explode(",", "application/pdf,application/octet-stream");
	foreach($pdfTypes as $type){
		if($type == $mime){
			return true;
		}
	}
	return false;
}

function validateSize($path, $fileSize = MAXUPLOADFILESIZE) {
	$fileRealSize = filesize($path);
	$maxSize =  $fileSize * 1024 * 1024;
	if ($fileRealSize > $maxSize){
		return false;
	}
	return true;
}

function rrmdir($dir) {
	//error_log("\n".$dir,3,'/var/log/nearpod/rmdir_log');

	//error_log("\n".print_r(debug_backtrace(),true),3,'/var/log/nearpod/rmdir_log');

	if (is_dir($dir)) {
		$objects = scandir($dir);
		foreach ($objects as $object) {
			if ($object != "." && $object != "..") {
				if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
			}
		}
		reset($objects);

		rmdir($dir);
	}
}

function rmfiles($dir, $pattern = "/.*/") {
	if (is_dir($dir)) {
		$objects = scandir($dir);
		foreach ($objects as $object) {
			if ($object != "." && $object != ".." && preg_match($pattern,$object)) {
				if (filetype($dir."/".$object) != "dir")
				unlink($dir."/".$object);
			}
		}
		reset($objects);
	}
}

function exploreDropboxRecursive($dropbox, $root = ""){
	$files = $dropbox->metaData($root);
	foreach ($files->contents as $file){
		if ($file->is_dir){
			echo "<DD> $file->path";
			exploreDropboxRecursive($dropbox,$file->path);
		} else {
			echo "<DD> $file->path";
		}
	}
}

function recursiveCopy($source, $dest, $diffDir = ''){
	$sourceHandle = opendir($source);
	if(!$diffDir)
	$diffDir = $source;

	if(!file_exists($dest . '/' . $diffDir)){
		mkdir($dest . '/' . $diffDir);
	}

	while($res = readdir($sourceHandle)){
		if($res == '.' || $res == '..')
		continue;

		if(is_dir($source . '/' . $res)){
			RecursiveCopy($source . '/' . $res, $dest, $diffDir . '/' . $res);
		} else {
			copy($source . '/' . $res, $dest . '/' . $diffDir . '/' . $res);

		}
	}
}

function is_email($email){
	$email = strtolower($email);
	$res = preg_match('/^[a-z0-9]+([\.]?[+a-z0-9_-]+)*@'.// usuario
				'[a-z0-9]+([\.]?[-]*[a-z0-9]+)*\.[a-z]{2,}$/', // server.
	$email);
	return $res;
}

function validateUrl($url){
	$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
	$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
	$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
	$regex .= "(\:[0-9]{2,5})?"; // Port
	$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
	$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
	$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor

	return preg_match("/^$regex$/", $url);
}

/*
 * @leadSource ("APP","ADMIN")
 *
 */

function createSForceContactFromUser($user){
	$record = new stdclass();
	$record->AccountName = $user->attributes->institute;
	$record->Email = $user->attributes->email;
	$record->LeadSource = $user->sfLeadSource;
	$record->FirstName = $user->attributes->firstName;
	$record->LastName = $user->attributes->lastName;
	$record->AmazonUserId = $user->attributes->id;
	$record->OptSignUp = "Yes";
	$record->UserId = $user->attributes->userName;
	$record->UserType = $user->attributes->sfType;
	$record->SchoolId = "";
	if($user->attributes->schoolId > 0){
		$school = new School($user->attributes->schoolId);
		$record->SchoolId = $school->attributes->sforceId;
	}

	$record->AmazonRole = UserRole::getName($user->attributes->roleId);

	return $record;
}

function getArrayFromAttributesFormultipleValuesWithSelect($attributes, $valueName, $comboName){
	$array = array();
	$counter = 0;
	foreach($attributes as $att){
		$array[$counter] = new stdClass();
		$array[$counter]->value = $att->attributes->$valueName;
		$array[$counter]->comboValue = $att->attributes->$comboName;
		$array[$counter]->id = $att->attributes->id;
		//$array[$counter]->lastValueType = $att->attributes->lastValueType;
		$counter++;
	}
	return $array;
}

function getRSSFeeds($rssURL) {
	$doc = new DOMDocument();
	$doc->load($rssURL);
	$arrFeeds = array();
	foreach ($doc->getElementsByTagName('item') as $node) {
		$itemRSS = array (
		      'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
		      'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
		      'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
		      'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
		);
		array_push($arrFeeds, $itemRSS);
	}
	return $arrFeeds;
}

function getLatestItem($rssURL){
	// 	$doc = new DOMDocument();
	// 	$doc->load($rssURL);
	// 	$arr = $doc->getElementsByTagName('item');
	// 	$node = $arr->item(0);
	// 	$itemRSS = array (
	// 			      'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
	// 			      'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
	// 			      'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
	// 			      'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
	// 		);

	// 	return $itemRSS;
	$feedArray = getRSSFeeds($rssURL);
	return $feedArray[0];
}

function getShortDescFromFeed($rssURL, $n = MAXRSSLENGHT){
	$itemArray = getLatestItem($rssURL);
	$desc = $itemArray["desc"];
	$desc = substr($desc,0,$n-3);
	$desc.="...";
	return $desc;
}

function generateImagesFromPDF($pdfPath, $toPath, $prePDFPath = "", $postPDFPath = ""){
	//$geometry = "";
	//if($size != ""){
	//	$geometry = " -thumbnail ".$size;
	//}

	//exec(IMAGEMAGICKCMD . " " . $prePDFPath . " \"{$pdfPath}\" {$postPDFPath} \"{$toPath}\"");
	return PsExecute(IMAGEMAGICKCMD . " " . $prePDFPath . " \"{$pdfPath}\" {$postPDFPath} \"{$toPath}\"", PDFTIMEOUT);

}


function getArrayFromAttributes($attributes, $name){
	$array = array();
	$counter = 0;
	foreach($attributes as $att){
		$array[$counter] = new stdClass();
		$array[$counter]->value = $att->attributes->$name;
		$array[$counter]->id = $att->attributes->id;
		$counter++;
	}
	return $array;

}

function getArrayForSelect($attributes, $name){
	$array = array();
	foreach($attributes as $att){
		$array[$att->attributes->id] = $att->attributes->$name;
	}
	return $array;

}

function call_rest_service_post_async($url, $params)
{
	$post_params = "";
	foreach ($params as $key => &$val) {
		if (is_array($val)) $val = implode(',', $val);
		$post_params[] = $key.'='.urlencode($val);
	}
	$post_string = implode('&', $post_params);

	$parts=parse_url($url);

	$fp = fsockopen($parts['host'],
	isset($parts['port'])?$parts['port']:80,
	$errno, $errstr, 30);


	$out = "POST ".$parts['path']." HTTP/1.1\r\n";
	$out.= "Host: ".$parts['host']."\r\n";
	$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
	$out.= "Content-Length: ".strlen($post_string)."\r\n";
	$out.= "Connection: Close\r\n\r\n";
	if (isset($post_string)) $out.= $post_string;
	fwrite($fp, $out);
	fclose($fp);
}

function call_rest_service_sync($url, $params, $format = 'xml', $method = "get") {
	$result = send_api_call($url, $params, $method);
	if($result){
		switch ($format){
			case "json":
				return json_decode($result,true);
				break;
			case "plain":
			case "xml":
				return $result;
				break;
			default:
				return false;
		}
	}else{
		return false;
	}
}

function url_exists($url) {
	$handle   = curl_init($url);
	if (false === $handle)
	{
		return false;
	}
	curl_setopt($handle, CURLOPT_HEADER, false);
	curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
	curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
	curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
	//curl_setopt($handle, CURLOPT_NOBODY, true);
	curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
	//curl_setopt($handle, CURLOPT_HTTPGET, true);
	$connectable = curl_exec($handle);
	curl_close($handle);
	return $connectable;
}

function http_build_query_for_curl( $arrays, &$new = array(), $prefix = null ) {

	if ( is_object( $arrays ) ) {
		$arrays = get_object_vars( $arrays );
	}

	foreach ( $arrays AS $key => $value ) {
		$k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key;
		if ( is_array( $value ) OR is_object( $value )  ) {
			http_build_query_for_curl( $value, $new, $k );
		} else {
			$new[$k] = $value;
		}
	}
}

function send_api_call($url, array $call, $method = "get") {
	$encoded_params = array();

	// URL encode all the parameters
	if($method == "get"){
		foreach ($call as $k => $v){
			$encoded_params[] = urlencode($k).'='.urlencode($v);
		}

		$params = implode('&', $encoded_params);

		// Put together the query string
		$url = $url . "?" . $params;
		$ch = curl_init ($url);
	}else{
		$ch = curl_init ($url);
		http_build_query_for_curl($call, $call);
		curl_setopt ($ch, CURLOPT_POST, true);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $call);
	}


	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);
	curl_setopt($ch, CURLOPT_TIMEOUT,30);
	if(isset($_SERVER["HTTP_USER_AGENT"])){
		curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
	}

	$loading = curl_exec ($ch) ;
	$headers = curl_getinfo($ch);

	curl_close ($ch) ;

	if ($headers["http_code"] != 200) //not OK
	return false;

	$content=trim($loading);

	return $content;
}


function getUrlWithHttp($url){
	if(!contains($url, "http")){
		$url = "http://" . $url;
	}

	return $url;
}

function tokenDecrypt($key, $str)
{
	$str = mcrypt_decrypt(MCRYPT_TRIPLEDES, $key, base64_decode($str), MCRYPT_MODE_ECB);
	$block = mcrypt_get_block_size('tripledes', 'ecb');
	$pad = ord($str[($len = strlen($str)) - 1]);
	return substr($str, 0, strlen($str) - $pad);
}




function tokenEncrypt($key, $data)
{
	$blockSize = mcrypt_get_block_size('tripledes', 'ecb');
	$len = strlen($data);
	$pad = $blockSize - ($len % $blockSize);
	$data .= str_repeat(chr($pad), $pad);
	$encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
	return base64_encode($encData);
}


function aes256Encrypt($key, $data) {
	if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
	$padding = 16 - (strlen($data) % 16);
	$data .= str_repeat(chr($padding), $padding);
	return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16)));
}

function aes256Decrypt($key, $data) {
	if(32 !== strlen($key)) $key = hash('SHA256', $key, true);
	$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
	base64_decode($data), MCRYPT_MODE_CBC, str_repeat("\0", 16));
	$padding = ord($data[strlen($data) - 1]);
	return substr($data, 0, -$padding);
}

function generateEncryptionToken(){
	$alphabet_array=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
	shuffle($alphabet_array);
	return implode('', array_slice( $alphabet_array, -5));
}

function setEncryptionToken(){
	//72hs
	$cache = Cache::getCacheInstance(259200);
	$token_number = rand(0, MAX_RANDOM);
	$key = "encryption_token_" . $token_number;
	$token = $cache->fetch($key,false);
	if(!$token || $token == ""){
		$token = generateEncryptionToken();
	}
	$cache->store($key, $token,false);
	RedisCache::setExpire($key, $token,259200);

	$token = array("token" => $token, "rd" => $token_number);
	return $token;
}


function setIsLightbox($value){
	global $CONFIG;
	$CONFIG->isLightbox = $value;
}

function getIsLightbox(){
	global $CONFIG;
	return $CONFIG->isLightbox;
}

function setTimezone(){
	if(getTimezoneOffset()){
		$timezones = array(
	        '-12'=>'Pacific/Kwajalein',
	        '-11'=>'Pacific/Samoa',
	        '-10'=>'Pacific/Honolulu',
	        '-9'=>'America/Juneau',
	        '-8'=>'America/Los_Angeles',
	        '-7'=>'America/Denver',
	        '-6'=>'America/Mexico_City',
	        '-5'=>'America/New_York',
	        '-4'=>'America/Caracas',
	        '-3.5'=>'America/St_Johns',
	        '-3'=>'America/Argentina/Buenos_Aires',
	        '-2'=>'Atlantic/Azores',// no cities here so just picking an hour ahead
	        '-1'=>'Atlantic/Azores',
	        '0'=>'Europe/London',
	        '1'=>'Europe/Paris',
	        '2'=>'Europe/Helsinki',
	        '3'=>'Europe/Moscow',
	        '3.5'=>'Asia/Tehran',
	        '4'=>'Asia/Baku',
	        '4.5'=>'Asia/Kabul',
	        '5'=>'Asia/Karachi',
	        '5.5'=>'Asia/Calcutta',
	        '6'=>'Asia/Colombo',
	        '7'=>'Asia/Bangkok',
	        '8'=>'Asia/Singapore',
	        '9'=>'Asia/Tokyo',
	        '9.5'=>'Australia/Darwin',
	        '10'=>'Pacific/Guam',
	        '11'=>'Asia/Magadan',
	        '12'=>'Asia/Kamchatka'
	        );

	        date_default_timezone_set($timezones[getTimezoneOffset()/60]);
	}
}

function setTimezoneOffset($offset){
	$_SESSION["localTimezoneOffset"] = $offset;
}

function getTimezoneOffset(){
	if(isset($_SESSION["localTimezoneOffset"])){
		return $_SESSION["localTimezoneOffset"];
	}

	return false;
}

function makeValuesReferenced($arr){
	$refs = array();
	foreach($arr as $key => $value)
	$refs[$key] = &$arr[$key];
	return $refs;

}

function aasort (&$array, $key) {
	$sorter=array();
	$ret=array();
	reset($array);
	foreach ($array as $ii => $va) {
		$sorter[$ii]=$va[$key];
	}
	asort($sorter);
	foreach ($sorter as $ii => $va) {
		$ret[$ii]=$array[$ii];
	}
	$array=$ret;
}


function getProvince($key){
	$provinces = getProvinces();
	return langEcho($provinces[$key]);
}

function getProvinces($country = "Argentina") {

	switch($country){

		case "Argentina":
			$provinces = array(

 					"BuenosAires" => "provinces:BuenosAires",
 					"CiudadAutonomaDeBuenosAires" => "provinces:CiudadAutonomaDeBuenosAires",
 					"Catamarca" => "provinces:Catamarca",
 					"Chaco" => "provinces:Chaco",
 					"Chubut" => "provinces:Chubut",
 					"Corrientes" => "provinces:Corrientes",
					"Cordoba" => "provinces:Cordoba",
  					"EntreRios" => "provinces:EntreRios",
  					"Formosa" => "provinces:Formosa",
  					"Jujuy" => "provinces:Jujuy",
  					"LaPampa" => "provinces:LaPampa",
 					"LaRioja" => "provinces:LaRioja",
					"Mendoza" => "provinces:Mendoza",
 					"Misiones" => "provinces:Misiones",
 					"Neuquen" => "provinces:Neuquen",
 					"RioNegro" => "provinces:RioNegro",
 					"Salta" => "provinces:Salta",
 					"SanJuan" => "provinces:SanJuan",
 					"SanLuis" => "provinces:SanLuis",
 					"SantaCruz" => "provinces:SantaCruz",
					"SantaFe" => "provinces:SantaFe",
 					"SantiagoDelEstero" => "provinces:SantiagoDelEstero",
 					"TierraDelFuego" => "provinces:TierraDelFuego",
 					"Tucuman" => "provinces:Tucuman",
			);

			return $provinces;

		default:
			return array();
	}

}

function getCountries () {
	$countries = array(
		"Afghanistan" => "countries:Afghanistan",
		"AfricanUnion" => "countries:AfricanUnion",
		"Albania" => "countries:Albania",
		"Algeria" => "countries:Algeria",
		"AmericanSamoa" => "countries:AmericanSamoa",
		"Andorra" => "countries:Andorra",
		"Angola" => "countries:Angola",
		"Anguilla" => "countries:Anguilla",
		"Antarctica" => "countries:Antarctica",
		"AntiguaAndBarbuda" => "countries:AntiguaAndBarbuda",
		"ArabLeague" => "countries:ArabLeague",
		"Argentina" => "countries:Argentina",
		"Armenia" => "countries:Armenia",
		"Aruba" => "countries:Aruba",
		"Australia" => "countries:Australia",
		"Austria" => "countries:Austria",
		"Azerbaijan" => "countries:Azerbaijan",
		"Bahamas" => "countries:Bahamas",
		"Bahrain" => "countries:Bahrain",
		"Bangladesh" => "countries:Bangladesh",
		"Barbados" => "countries:Barbados",
		"Belarus" => "countries:Belarus",
		"Belgium" => "countries:Belgium",
		"Belize" => "countries:Belize",
		"Benin" => "countries:Benin",
		"Bermuda" => "countries:Bermuda",
		"Bhutan" => "countries:Bhutan",
		"Bolivia" => "countries:Bolivia",
		"BosniaAndHerzegovina" => "countries:BosniaAndHerzegovina",
		"Botswana" => "countries:Botswana",
		"Brazil" => "countries:Brazil",
		"Brunei" => "countries:Brunei",
		"Bulgaria" => "countries:Bulgaria",
		"BurkinaFaso" => "countries:BurkinaFaso",
		"Burundi" => "countries:Burundi",
		"Cambodja" => "countries:Cambodja",
		"Cameroon" => "countries:Cameroon",
		"Canada" => "countries:Canada",
		"CapeVerde" => "countries:CapeVerde",
		"CaymanIslands" => "countries:CaymanIslands",
		"CentralAfricanRepublic" => "countries:CentralAfricanRepublic",
		"Chad" => "countries:Chad",
		"Chile" => "countries:Chile",
		"China" => "countries:China",
		"Colombia" => "countries:Colombia",
		"Commonwealth" => "countries:Commonwealth",
		"Comoros" => "countries:Comoros",
		"Congo-Brazzaville" => "countries:Congo-Brazzaville",
		"Congo-Kinshasa(Zaire)" => "countries:Congo-Kinshasa(Zaire)",
		"CookIslands" => "countries:CookIslands",
		"CostaRica" => "countries:CostaRica",
		"CotedIvoire" => "countries:CotedIvoire",
		"Croatia" => "countries:Croatia",
		"Cuba" => "countries:Cuba",
		"Cyprus" => "countries:Cyprus",
		"CzechRepublic" => "countries:CzechRepublic",
		"Denmark" => "countries:Denmark",
		"Djibouti" => "countries:Djibouti",
		"DominicanRepublic" => "countries:DominicanRepublic",
		"Dominica" => "countries:Dominica",
		"Ecuador" => "countries:Ecuador",
		"Egypt" => "countries:Egypt",
		"ElSalvador" => "countries:ElSalvador",
		"England" => "countries:England",
		"EquatorialGuinea" => "countries:EquatorialGuinea",
		"Eritrea" => "countries:Eritrea",
		"Estonia" => "countries:Estonia",
		"Ethiopia" => "countries:Ethiopia",
		"EuropeanUnion" => "countries:EuropeanUnion",
		"Faroes" => "countries:Faroes",
		"Fiji" => "countries:Fiji",
		"Finland" => "countries:Finland",
		"France" => "countries:France",
		"Gabon" => "countries:Gabon",
		"Gambia" => "countries:Gambia",
		"Georgia" => "countries:Georgia",
		"Germany" => "countries:Germany",
		"Ghana" => "countries:Ghana",
		"Gibraltar" => "countries:Gibraltar",
		"Greece" => "countries:Greece",
		"Greenland" => "countries:Greenland",
		"Grenada" => "countries:Grenada",
		"Guadeloupe" => "countries:Guadeloupe",
		"Guademala" => "countries:Guademala",
		"Guam" => "countries:Guam",
		"Guernsey" => "countries:Guernsey",
		"Guinea-Bissau" => "countries:Guinea-Bissau",
		"Guinea" => "countries:Guinea",
		"Guyana" => "countries:Guyana",
		"Haiti" => "countries:Haiti",
		"Honduras" => "countries:Honduras",
		"HongKong" => "countries:HongKong",
		"Hungary" => "countries:Hungary",
		"Iceland" => "countries:Iceland",
		"India" => "countries:India",
		"Indonesia" => "countries:Indonesia",
		"Iran" => "countries:Iran",
		"Iraq" => "countries:Iraq",
		"Ireland" => "countries:Ireland",
		"IslamicConference" => "countries:IslamicConference",
		"IsleofMan" => "countries:IsleofMan",
		"Israel" => "countries:Israel",
		"Italy" => "countries:Italy",
		"Jamaica" => "countries:Jamaica",
		"Japan" => "countries:Japan",
		"Jersey" => "countries:Jersey",
		"Jordan" => "countries:Jordan",
		"Kazakhstan" => "countries:Kazakhstan",
		"Kenya" => "countries:Kenya",
		"Kiribati" => "countries:Kiribati",
		"Kosovo" => "countries:Kosovo",
		"Kuwait" => "countries:Kuwait",
		"Kyrgyzstan" => "countries:Kyrgyzstan",
		"Laos" => "countries:Laos",
		"Latvia" => "countries:Latvia",
		"Lebanon" => "countries:Lebanon",
		"Lesotho" => "countries:Lesotho",
		"Liberia" => "countries:Liberia",
		"Libya" => "countries:Libya",
		"Liechtenstein" => "countries:Liechtenstein",
		"Lithuania" => "countries:Lithuania",
		"Luxembourg" => "countries:Luxembourg",
		"Macao" => "countries:Macao",
		"Macedonia" => "countries:Macedonia",
		"Madagascar" => "countries:Madagascar",
		"Malawi" => "countries:Malawi",
		"Malaysia" => "countries:Malaysia",
		"Maldives" => "countries:Maldives",
		"Mali" => "countries:Mali",
		"Malta" => "countries:Malta",
		"MarshallIslands" => "countries:MarshallIslands",
		"Martinique" => "countries:Martinique",
		"Mauritania" => "countries:Mauritania",
		"Mauritius" => "countries:Mauritius",
		"Mexico" => "countries:Mexico",
		"Micronesia" => "countries:Micronesia",
		"Moldova" => "countries:Moldova",
		"Monaco" => "countries:Monaco",
		"Mongolia" => "countries:Mongolia",
		"Montenegro" => "countries:Montenegro",
		"Montserrat" => "countries:Montserrat",
		"Morocco" => "countries:Morocco",
		"Mozambique" => "countries:Mozambique",
		"Myanmar(Burma)" => "countries:Myanmar(Burma)",
		"Namibia" => "countries:Namibia",
		"Nauru" => "countries:Nauru",
		"Nepal" => "countries:Nepal",
		"NetherlandsAntilles" => "countries:NetherlandsAntilles",
		"Netherlands" => "countries:Netherlands",
		"NewCaledonia" => "countries:NewCaledonia",
		"NewZealand" => "countries:NewZealand",
		"Nicaragua" => "countries:Nicaragua",
		"Nigeria" => "countries:Nigeria",
		"Niger" => "countries:Niger",
		"NorthernCyprus" => "countries:NorthernCyprus",
		"NorthernIreland" => "countries:NorthernIreland",
		"NorthKorea" => "countries:NorthKorea",
		"Norway" => "countries:Norway",
		"OlimpicMovement" => "countries:OlimpicMovement",
		"Oman" => "countries:Oman",
		"Pakistan" => "countries:Pakistan",
		"Palau" => "countries:Palau",
		"Palestine" => "countries:Palestine",
		"Panama" => "countries:Panama",
		"PapuaNewGuinea" => "countries:PapuaNewGuinea",
		"Paraguay" => "countries:Paraguay",
		"Peru" => "countries:Peru",
		"Philippines" => "countries:Philippines",
		"Poland" => "countries:Poland",
		"Portugal" => "countries:Portugal",
		"PuertoRico" => "countries:PuertoRico",
		"Qatar" => "countries:Qatar",
		"Reunion" => "countries:Reunion",
		"Romania" => "countries:Romania",
		"RussianFederation" => "countries:RussianFederation",
		"Rwanda" => "countries:Rwanda",
		"SaintLucia" => "countries:SaintLucia",
		"Samoa" => "countries:Samoa",
		"SanMarino" => "countries:SanMarino",
		"SaoTomeAndPrincipe" => "countries:SaoTomeAndPrincipe",
		"SaudiArabia" => "countries:SaudiArabia",
		"Scotland" => "countries:Scotland",
		"Senegal" => "countries:Senegal",
		"Serbia" => "countries:Serbia",
		"Seyshelles" => "countries:Seyshelles",
		"SierraLeone" => "countries:SierraLeone",
		"Singapore" => "countries:Singapore",
		"Slovakia" => "countries:Slovakia",
		"Slovenia" => "countries:Slovenia",
		"SolomonIslands" => "countries:SolomonIslands",
		"Somalia" => "countries:Somalia",
		"Somaliland" => "countries:Somaliland",
		"SouthAfrica" => "countries:SouthAfrica",
		"SouthKorea" => "countries:SouthKorea",
		"Spain" => "countries:Spain",
		"SriLanka" => "countries:SriLanka",
		"StKittsAndNevis" => "countries:StKittsAndNevis",
		"StVincentAndtheGrenadines" => "countries:StVincentAndtheGrenadines",
		"Sudan" => "countries:Sudan",
		"Suriname" => "countries:Suriname",
		"Swaziland" => "countries:Swaziland",
		"Sweden" => "countries:Sweden",
		"Switzerland" => "countries:Switzerland",
		"Syria" => "countries:Syria",
		"Tahiti(FrenchPolinesia)" => "countries:Tahiti(FrenchPolinesia)",
		"Taiwan" => "countries:Taiwan",
		"Tajikistan" => "countries:Tajikistan",
		"Tanzania" => "countries:Tanzania",
		"Thailand" => "countries:Thailand",
		"Timor-Leste" => "countries:Timor-Leste",
		"Togo" => "countries:Togo",
		"Tonga" => "countries:Tonga",
		"TrinidadAndTobago" => "countries:TrinidadAndTobago",
		"Tunisia" => "countries:Tunisia",
		"Turkey" => "countries:Turkey",
		"Turkmenistan" => "countries:Turkmenistan",
		"TurksandCaicosIslands" => "countries:TurksandCaicosIslands",
		"Tuvalu" => "countries:Tuvalu",
		"Uganda" => "countries:Uganda",
		"Ukraine" => "countries:Ukraine",
		"UnitedArabEmirates" => "countries:UnitedArabEmirates",
		"UnitedKingdom(GreatBritain)" => "countries:UnitedKingdom(GreatBritain)",
		"UnitedNations" => "countries:UnitedNations",
		"UnitedStatesofAmerica" => "countries:UnitedStatesofAmerica",
		"Uruguay" => "countries:Uruguay",
		"Uzbekistan" => "countries:Uzbekistan",
		"Vanutau" => "countries:Vanutau",
		"VaticanCity" => "countries:VaticanCity",
		"Venezuela" => "countries:Venezuela",
		"VietNam" => "countries:VietNam",
		"VirginIslandsBritish" => "countries:VirginIslandsBritish",
		"VirginIslandsUS" => "countries:VirginIslandsUS",
		"Wales" => "countries:Wales",
		"WesternSahara" => "countries:WesternSahara",
		"Yemen" => "countries:Yemen",
		"Zambia" => "countries:Zambia",
		"Zimbabwe" => "countries:Zimbabwe"
		);
		return $countries;
}


function notifyBroadcastMessageAllUsers($distance = 1000){
	$userFinder = new User();
	$users = $userFinder->search('`type` = 1');

	foreach ($users as $user){
		notifyBroadcastMessage($user, $distance);
	}
}

/*
 * Notifica via gcm al usuario logueado si tiene mensajes de broadcast nuevos
 */
function notifyBroadcastMessage(User $user = null, $distance = 1000){
	if (!isset($user)){
		$user = getUserFromInput();
	}
	//solo notifico a usuarios que no son empresas
	if ($user->type != 1){
		return;
	}

	$companyMesagges = new CompanyMessages();
	$messages = $companyMesagges->getUnnotifiedBroadcastMessages($user, $distance);
	$amountToNotify = count($messages);

	if ($amountToNotify == 0){
		return;
	}

	require_once dirname(__FILE__).'/../gcm_php_server/GCM.php';

	$gcm = new GCM();

	$registation_ids = array($user->gcm_regid);
	//$registation_ids = array("APA91bGWTPjy7XGc5MsgRN_HBk3megfLUFEUtBSGUoVOoUu91tCfGfRRmqo_hdTwxeYnVH7PbOi01kSJh3clX7r8yIhmwXWLiX4COg-tl3kdFR8QH-sDUl9Xbo_QZmtFD5Vl5JpUyyu3jqSf2YuQQnueF8dvNs4kTakkaOeAOlSlt8l-XzEYvvI");
	
	if ($amountToNotify > 1){
		$payload = "Tenes $amountToNotify mensajes nuevos";
	}else{
		$payload = "Tenes $amountToNotify mensaje nuevo";
	}
	
	$message = Array(
		"errorNum" => 0, 
		"message" => "broadcast:notifications", 
		//"payload" => $companyMesagges->buildMessagesResponseFromObj($messages)
		"payload" => $payload
	);

	$result = $gcm->send_notification($registation_ids, $message);
}

function getUserFromInput(){
	$username = getInput("username", null);
	if (isset($username)){
		$user = User::getByUserName($username);
		if ($user){
			return $user;
		}
	}

	response("", "", 1, langEcho("username:required"));
}

?>
